import React, {useEffect, useState} from "react";
import {Button, Input, Form, Space, List, Select, Card, Switch} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import styles from './index.module.css'
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";
import {generateUniqueId} from "@/utils/Z.ts";


interface MyComponentProps {
    bpmnInstance: any;
}

interface DefaultOptionType {
    value: string;
    label: string;
}

interface ExecutionListenerElement {
    $type: string;
    event: string;
    class?: string;
    expression?: string;
    delegateExpression?: string;
}

interface EventConfig {
    // eventDefinitionType: 'message' | 'signal' | 'timer';
    eventDefinitionType:any;
    messageName?: string;
    signalName?: string;
    timerDefinitionType?: any;
    timerDefinition?: string;
}

// 事件配置组件
const EventConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const {bpmnInstance} = props
    const {modeling, modeler, moddle, bpmnElement = {}, elementRegistry, bpmnFactory} = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();

    const [eventConfig, setEventConfig] = useState<EventConfig>({
        eventDefinitionType: 'message',
        messageName: '',
        signalName: '',
        timerDefinitionType: '',
        timerDefinition: '',
    });
    useEffect(() => {
        if (bpmnElement.businessObject) {
            if (bpmnElement.businessObject?.eventDefinitions?.length > 0) {
                const definition = bpmnElement.businessObject.eventDefinitions[0] || []
                console.log("bpmnElement.businessObject", definition);
                if (definition.$type === 'bpmn:MessageEventDefinition') {
                    eventConfig.eventDefinitionType = 'message'
                    eventConfig.messageName = definition.messageRef?.name || ''
                } else if (definition.$type === 'bpmn:SignalEventDefinition') {
                    eventConfig.eventDefinitionType = 'signal'
                    eventConfig.signalName = definition.signalRef?.name || ''
                } else if (definition.$type === 'bpmn:TimerEventDefinition') {
                    eventConfig.eventDefinitionType = 'timer'
                    if (definition.timeDate) {
                        eventConfig.timerDefinitionType = 'timeDate'
                        eventConfig.timerDefinition = definition.timeDate.body || ''
                    } else if (definition.timeDuration) {
                        eventConfig.timerDefinitionType = 'timeDuration'
                        eventConfig.timerDefinition = definition.timeDuration.body || ''
                    } else if (definition.timeCycle) {
                        eventConfig.timerDefinitionType = 'timeCycle'
                        eventConfig.timerDefinition = definition.timeCycle.body || ''
                    }
                }
            } else {
                eventConfig.eventDefinitionType = ''
                eventConfig.messageName = ''
                eventConfig.signalName = ''
                eventConfig.timerDefinitionType = ''
                eventConfig.timerDefinition = ''
            }
        }
        setBaseInfo({
            ...bpmnElement.businessObject,
        })

    }, [bpmnElement.businessObject]);
    // 更新数据
    const handleEventChange = () => {
        if (!bpmnElement || !modeler) return;
        const eventDefinitions = [];
        if (eventConfig.eventDefinitionType === 'message') {

            const messageRef = moddle.create('bpmn:Message', {
                name: eventConfig.messageName,
                id: generateUniqueId("Message")//必须有id,不然无法关联
            });
            eventDefinitions.push(
                moddle.create('bpmn:MessageEventDefinition',
                    {
                        id: generateUniqueId("Message"),
                        messageRef
                    },
                ),
            );
        } else if (eventConfig.eventDefinitionType === 'signal') {
            const signalRef = moddle.create('bpmn:Signal', {
                name: eventConfig.signalName,
                id: generateUniqueId("Message"),//必须有id,不然无法关联
            });
            eventDefinitions.push(
                moddle.create('bpmn:SignalEventDefinition',
                    {
                        id: generateUniqueId("Message"),
                        signalRef
                    },
                ),
            );
        } else if (eventConfig.eventDefinitionType === 'timer') {
            const timerDefinition: Record<string, unknown> = {};
            const timeType = eventConfig.timerDefinitionType;
            if (timeType) {
                timerDefinition[timeType] = moddle.create('bpmn:FormalExpression', {
                    body: eventConfig.timerDefinition,
                });
            }
            eventDefinitions.push(moddle.create('bpmn:TimerEventDefinition', timerDefinition));
        }
        modeling.updateProperties(bpmnElement, {
            eventDefinitions,
        });
    };

    // 示例：更新 eventConfig 的方法
    const updateEventConfig = (newConfig: Partial<EventConfig>) => {
        console.log(newConfig, 'newConfig')
        setEventConfig((prevConfig) => (
            {
                ...prevConfig,
                ...newConfig,
            }));
        handleEventChange()
    };

    const EventTypeList: DefaultOptionType[] = [
        {
            value: "message",
            label: '消息事件',
        }, {
            value: "signal",
            label: '信号事件',
        }, {
            value: "timer",
            label: '定时事件',
        },
    ]
    const timerDefinitionTypeList: DefaultOptionType[] = [
        {
            value: "timeDate",
            label: '日期',
        }, {
            value: "timeDuration",
            label: '持续时间',
        }, {
            value: "timeCycle",
            label: '循环',
        },
    ]
    const assigneeTypeMap = EventTypeList.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
    }, {} as Record<string, string>);
    return (
        <div className={baseInformationClass.listenerContainer}>
            <Card
                className={baseInformationClass.CardClass}
                title={`表单配置`}
                extra={null}>
                <Form>
                    <Form.Item
                        label="事件类型"
                        labelCol={{span: 6}}
                        wrapperCol={{span: 18}}>
                        <Select
                            value={[eventConfig.eventDefinitionType]}
                            style={{width: '80%'}}
                            options={EventTypeList}
                            onChange={(e) => updateEventConfig({eventDefinitionType: e})}

                        />
                    </Form.Item>
                    {eventConfig.eventDefinitionType === 'message' && (<Form.Item
                        label="消息名称"
                        labelCol={{span: 6}}
                        wrapperCol={{span: 18}}>
                        <Input
                            value={eventConfig.messageName}
                            onChange={(e) => updateEventConfig({messageName: e.target.value})}
                        />
                    </Form.Item>)}
                    {eventConfig.eventDefinitionType === 'signal' && (<Form.Item
                            label="信号名称"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Input
                                value={eventConfig.signalName}
                                onChange={(e) => updateEventConfig({signalName: e.target.value})}
                            />
                        </Form.Item>
                    )}
                    {eventConfig.eventDefinitionType === 'timer' && (<> <Form.Item
                        label="时间类型"
                        labelCol={{span: 6}}
                        wrapperCol={{span: 18}}>
                        <Select
                            value={[eventConfig.timerDefinitionType]}
                            style={{width: '80%'}}
                            options={timerDefinitionTypeList}
                            onChange={(e) => updateEventConfig({timerDefinitionType: e})}

                        />
                    </Form.Item>
                        <Form.Item
                            label="时间表达式"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Input
                                value={eventConfig.timerDefinition}
                                onChange={(e) => updateEventConfig({timerDefinition: e.target.value})}
                            />
                        </Form.Item></>)}

                </Form>
                <button onClick={handleEventChange}>Update Event</button>
            </Card>

        </div>
    );
};

export default EventConfigurationView;
